package com.baosight.risk.service.rifi.impl;

import com.baosight.risk.api.fltd.FlaaNodeAuthoService;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.rifi.RifiRiskFinishService;
import com.baosight.risk.api.workflow.AfterHandler;
import com.baosight.risk.api.workflow.UpdateHandler;
import com.baosight.risk.api.xtdc.XtdcAttachService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.mapper.fltd.FlaaNodeAuthoMapper;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.mapper.rifi.RifiRiskFinishMapper;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.fltd.vo.NodeTransitionVO;
import com.baosight.risk.service.rifi.entity.RifiRiskFinish;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.rire.vo.RiskWarningStatusVO;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class RifiRiskServiceSubImpl extends BaseServiceImpl<RifiRiskFinish> implements UpdateHandler, AfterHandler {
    @Autowired
    private RifiRiskFinishMapper rifiRiskFinishMapper;

    @Autowired
    private RiimRiskImportMapper riimRiskImportMapper;

    @Autowired
    private XtzyUserMapper xtzyUserMapper;

    @Autowired
    private FltdProcessService fltdProcessService;

    @Autowired
    private FlaaNodeAuthoMapper flaaNodeAuthoMapper;
    @Autowired
    private FlaaNodeAuthoService flaaNodeAuthoService;
    @Autowired
    private XtdcAttachService xtdcAttachService;


    @Autowired
    private FltdTaskMapper fltdTaskMapper;
    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * bizName 业务名称
     * taskGuid 项目id(重点风险id)
     * context 审批意见
     * submitType 提交、回退、结束, 值：(submit, reject, end)
     */
    @Override
    public boolean doAfter(Map<String, Object> params) {
        try{
            RifiRiskFinish finishParam=new RifiRiskFinish();
            finishParam.setId(params.get("bizGuid").toString());
            RifiRiskFinish riskFinish=rifiRiskFinishMapper.selectOne(finishParam);
            if(!ObjectUtils.isEmpty(riskFinish)){
                //根据重点风险ID,查询重点风险清单（t_riim_risk_import）
                RiimRiskImport riskImport=new RiimRiskImport();
                riskImport.setId(riskFinish.getImportGuid());
                RiimRiskImport subRiskImport= riimRiskImportMapper.selectOne(riskImport);
                //查询上级单位的重点风险清单
                if(!StringUtils.isEmpty(subRiskImport.getParentId())){
                    RiimRiskImport parentRiskImport=new RiimRiskImport();
                    parentRiskImport.setId(subRiskImport.getParentId());
                    RiimRiskImport parentImport=riimRiskImportMapper.selectOne(parentRiskImport);
                    if("B09".equals(parentImport.getStatus())){
                        RifiRiskFinish parentFinish=rifiRiskFinishMapper.selectByImportGuid(parentImport.getId());
                        //如果上级风险报告的当前节点为待填报（B01），则执行数据复制、调用上级单位工作流；
                        // 如果上级风险报告的当前节点为待填报（B03、B04、B05、B06、B07），程序结束；
                        //如果上级单位的当前节点为其他，则提示“宝钢股份重点风险档案的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流”
                        if("B01".equals(parentFinish.getFinishStatus())){
                            this.submit(parentFinish,parentImport);
                        }else if("B03".equals(parentFinish.getFinishStatus())||"B04".equals(parentFinish.getFinishStatus())||"B05".equals(parentFinish.getFinishStatus())||"B06".equals(parentFinish.getFinishStatus())||"B07".equals(parentFinish.getFinishStatus())){
                            return false;
                        }else {
                            throw new Exception("宝钢股份重点风险档案的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流");
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error("扭转流程异常："+e.getMessage());
            return false;
        }

        return true;
    }

    @Override
    public boolean updateStatus(Map<String, Object> params) {
        return false;
    }

    private void submit(RifiRiskFinish parentFinish, RiimRiskImport parentImport){
        if(com.baosight.risk.common.utils.StringUtils.isNotEmpty(parentImport.getDutyUserCode())){
            XtzyUser xtzyUser = xtzyUserMapper.selectByName(parentImport.getDutyUserCode());
            FltdTaskVO paramTask=new FltdTaskVO();
            paramTask.setFlowNo("fengxianjieti");
            paramTask.setBizGuid(parentFinish.getId());
            paramTask.setNodeCode(parentFinish.getFinishStatus());
            paramTask.setStatus("open");
            List<FltdTask> taskList = fltdTaskMapper.selectTaskList(paramTask);
            if(taskList.size()>0){
                FltdTaskVO taskVoParam=new FltdTaskVO();
                BeanUtils.copyBeanProp(taskVoParam, taskList.get(0));
                try {
                    FltdTask updateTask=new FltdTask();
                    updateTask.setTodoGuid(taskVoParam.getTodoGuid());
                    //走绿色通道
                    updateTask.setGreenFlag("G");
                    fltdTaskMapper.updateByPrimaryKeySelective(updateTask);
                    taskVoParam.setGreenFlag("G");

                    //获取下一节点审批人
                    Map<String, Object> resultMap = flaaNodeAuthoService.getNextUser(taskVoParam, xtzyUser);
                    List<XtzyUser> authUsers = (List<XtzyUser>)resultMap.get("authUsers");
                    if(CollectionUtils.isNotEmpty(authUsers)){
                        taskVoParam.setCustomUsers(authUsers);

                        //查询指定节点的下一个节点及转移路线
                        String processDefId = fltdProcessService.getProcessDefId(taskVoParam.getProcGuid());
                        NodeTransitionVO nextTransition = flaaNodeAuthoMapper.nextOneNodeTransition(processDefId, "submit-G-1");
                        taskVoParam.setSubmitButton(nextTransition);

                        fltdProcessService.doSubmit(xtzyUser,taskVoParam);
                    }

                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
    }

}
